package com.sc.admin.base.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sc.admin.base.mapper.RouteMapper;
import com.sc.admin.base.service.IRouteService;
import com.sc.admin.base.vo.route.RouteListVO;
import com.sc.common.entity.RouteEntity;
import com.sc.common.service.AbstractBaseService;
import com.sc.core.util.DataAutoSearch.DataAutoSearch;
import com.sc.core.util.TreeHandler;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;

@Primary
@Service
public class RouteServiceImpl extends AbstractBaseService<RouteMapper, RouteEntity> implements IRouteService {

    @Override
    public List<RouteListVO> getMenu() {
        LambdaQueryWrapper<RouteEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RouteEntity::getType, RouteEntity.RouteTypeEnum.LEFT_MENU.getValue());
        List<RouteEntity> menusRoute = baseMapper.selectList(wrapper);

        return routeTreeHandle(menusRoute);
    }

    @Override
    public List<RouteListVO> getList(DataAutoSearch dataAutoSearch) {
        LambdaQueryWrapper<RouteEntity> routeEntityQueryWrapper = new LambdaQueryWrapper<>();
        routeEntityQueryWrapper.orderByDesc(RouteEntity::getWeigh);
        routeEntityQueryWrapper.orderByDesc(RouteEntity::getId);
        List<RouteEntity> routs = baseMapper.selectList(routeEntityQueryWrapper);

        return routeTreeHandle(routs);
    }

    private List<RouteListVO> routeTreeHandle(List<RouteEntity> routs) {
        List<RouteListVO> list = TreeHandler.<RouteEntity, RouteListVO>of(routs)
                .setTargetPrimaryMethod(RouteListVO::id)
                .getTree(RouteListVO.class)
                .each(routeListVO -> {
                    if (!routeListVO.children().isEmpty()) {
                        routeListVO.children().sort((o1, o2) -> o2.weigh() - o1.weigh());
                    }
                    return routeListVO;
                })
                .toList();
        list.sort((o1, o2) -> o2.weigh() - o1.weigh());
        return list;
    }
}
